<?php

chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir("../");
$path3 = getcwd();
chdir(dirname(__FILE__));
#debug($path3 , $path2);
include_once $path3."/lib/core.class.php";;


class TypeDiscounts extends IPlugin 
{
    var $color;
    
    function TypeDiscounts($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__) . "/tpl";
        $this->color = "blue";
    }
    
    function getPluginTag() { return "discounts_type"; }
    function getPluginName() { return "Discounts Plugin"; }
    function getPluginVersion() { return "1.0.0"; }
    
    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuTitle", "MenuBlockTitle");
        }
        $result = "";
        switch ($p)
        {
            case "MenuBlockTitle": { return "Discounts management"; } break;
            case "MenuTitle" : { return "Discounts Types"; } break;
        };
        return $result;
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------

    function doAction($params)
    {
        if(null != ($result = IPlugin::doAction($params)))
        {
            return $result;
        }

        $core = getCoreInstance();
        $db = $core->getProperty("db");

        switch ($_POST["event"]) 
        {
            case "doSubmitEditDiscountType" :

                    $items_list = "";
                    if (!isset($_POST['selected_items_list']))
                        $items_list = "0";
                    else
                    {
                        foreach ($_POST['selected_items_list'] as $item)
                            $items_list .= ($items_list == "" ? "" : ",") . $item;
                    }
            
                    $db->Exec("update discount_type set title = '" . str2db($_POST['title']) . "', group_with = '{$items_list}' where id_type = {$_POST[id]}");
                    break;
            
            case "doSubmitAddDiscountType" :

                    $items_list = "";
                    if (!isset($_POST['selected_items_list']))
                        $items_list = "0";
                    else
                    {
                        foreach ($_POST['selected_items_list'] as $item)
                            $items_list .= ($items_list == "" ? "" : ",") . $item;
                    }
            
                    $db->Exec("insert into discount_type (title, group_with) values ('" . str2db($_POST['title']) . "', '{$items_list}')");
                    break;

            default: break;
        }


        switch ($_POST["action"]) 
        {
            case "insert_before" :

                    $chbx = $_POST['chbx'];
                    $sibling_count = $_POST['sibling_count'];
                    
                    $not_in ="";
                    for($i = 0; $i<sizeof($chbx); $i++){
                        $not_in .= ($i == 0 ? "" : ", ") . "'{$chbx[$i]}' " ;
                    }
                    $q=" select id_type ,sibling from discount_type where sibling >= '{$sibling_count}' and id_type not in ({$not_in}) order by sibling";
                    $res = $db->getAll($q);
                    
                    $arg = array();
                    for($i = 0 ; $i <sizeof($chbx);$i++){
                        $arg[$i] = array($sibling_count++,$chbx[$i]);
                    }
                    for($i = 0 ; $i <sizeof($res);$i++){
                        $arg[] = array($sibling_count++,$res[$i]['id_type']);
                    }
                    $db->Exec("update discount_type set sibling=? where id_type=?",0, $arg);

                    break;

            case "insert_after" :

                    $chbx = $_POST['chbx'];
                    $sibling_count = $_POST['sibling_count'];
                    
                    $not_in =="";
                    for($i = 0; $i<sizeof($chbx); $i++){
                        $not_in .= ($i == 0 ? "" : ", ") . "'{$chbx[$i]}' " ;
                    }
                    $q=" select id_type ,sibling from discount_type where sibling> '{$sibling_count}' and id_type not in ({$not_in})";
                    $res = $db->getAll($q);
                    
                    $arg = array();
                    for($i = 0 ; $i <sizeof($chbx);$i++){
                        $arg[$i] = array(++$sibling_count,$chbx[$i]);
                    }
                    for($i = 0 ; $i <sizeof($res);$i++){
                        $arg[] = array(++$sibling_count,$res[$i]['id_type']);
                    }
                    $db->Exec("update discount_type set sibling=? where id_type=?",0, $arg);

                    break;

            case "sibling_delete" :

                    $chbx = $_POST['chbx'];
                    $sibling_count = $_POST['sibling_count'];
                    
                    $in_chk = "";
                    for($i = 0; $i<sizeof($chbx); $i++){
                        $in_chk .= ($i == 0 ? "" : ", ") . "'{$chbx[$i]}' " ;
                    }
                    $q = "delete from discount_type where id_type in ({$in_chk})";
                    $db->Exec($q);
                    $q = "delete from discount where id_type in ({$in_chk})";
                    $db->Exec($q);

                    break;


            default: break;
        }
        
    }



    // ----------------------------------------------------------------------------------
    // --- [ Render pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------

    function Render($params)
    {
        global $_G;
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }
        
        $core = &getCoreInstance();
        $db = $core->getProperty("db");
        $framework = $core->getProperty("framework");
        $render = $framework->smarty;
        $render->assign("baseurl", "?".$this->getURL()."&page=".$_G["page"]);

        $page = "";

        switch ($_G["page"]) 
        {
            case "discount_type" :
                $this->renderDiscountType($render, $db, $core);
                $page = "type_discount_view.tpl.php";
                 break;

            case "add" :
                $this->renderDiscountTypeAdd($render, $db, $core);
                $page = "type_discount_edit.tpl.php";
                 break;

            case "edit_type" :
                $this->renderDiscountTypeEdit($render, $db, $core);
                $page = "type_discount_edit.tpl.php";
                 break;
            
            default: 
                $this->renderDiscountType($render, $db, $core);
                $page = "type_discount_view.tpl.php";
                 break;
        }

        return $render->fetch("file:" . $this->tplfolder . "/" . $page);
    }
    
    // ----------------------------------------------------------------------------------
    // --- [ Render Discount Type View Page ] ---------------------------------------------------
    // ----------------------------------------------------------------------------------
    function cb_rndDT($data)
    {
        $dt = array(
                array("<input type='checkbox' name='chbx[]' value='{$data[id_type]}' />", "align='center' "),
                array($data["id_type"], "align=\"center\""),
                array($data["title"], ""),
                array($data["sibling"], ""),
                array("<a href=\"?".$this->getURL()."&page=edit_type&id={$data[id_type]}\">edit</a>","align=\"center\""),
                );
        return $dt;
    }


    function renderDiscountType(&$render, &$db, &$core)
    {
        $pg = &$core->getSnippet("paginator");

        $params = array(
                    "cb_class" => &$this,
                    "cb_func" => cb_rndDT,
                    "urlbase" => $this->getURL(),
                    "caption" => "Discounts Types",
                    "emptymsg" => "No discounts types created yet",
                    "header" => array("Check", "ID", "Discount type Title", "Sibling", "Action"),
                    "items" => "",
                    "source" => "sql", // -- sql, array
                    "sql_items" => "select id_type, title, sibling  from discount_type order by sibling",
                    "sql_count" => "select count(*) from discount_type",
                    "ippg" => 15, // -- items per page
                    "nppv" => 5, // -- number pages per view
                    );

        $HTML = $pg->Render($params);
        $render->assign("discounts", $HTML);


        $sb = &$core->getSnippet("sibling");
        $sibling_params = array(
            "action"        =>"removeWrongSibling",
            "table"         =>"discount_type",
            "sField"        =>"sibling", // ordering field
            "sId"           =>"id_type", 
            "sParentId"     =>"parent_id", 
            "sOrderBy"      =>" order by title", 
        );
        $sb -> doAction($sibling_params);// remove sibling = -1


         $sql_action = "select id_type ,sibling, title from discount_type order by sibling ";
         $res_action = $db->getAll($sql_action );
         $res_action_str = "";
         for($i= 0 ; $i < sizeof($res_action) ; $i++ )
         {
            $res_action_str .= join("|",$res_action[$i]);
            if($i != sizeof($res_action)-1)
            {
                $res_action_str .="||";
            }
         }

        $params = array
        (
            "action_url"    => "?".$this->getURL(),
            "action_list"   => array("insert_after","insert_before","sibling_delete"),
            "insert_list_str" => $res_action_str
         );
 
        $render->assign('action_url', "?".$this->getURL());
         
        $SB_HTML = $sb->Render($params);
        $render->assign('sibling',$SB_HTML);
     }

    // ----------------------------------------------------------------------------------
    // --- [ Render Discount Type Edit Page ] ---------------------------------------------------
    // ----------------------------------------------------------------------------------

    function renderDiscountTypeEdit(&$render, &$db, &$core)
    {
        $arr_data = ArrayDb2Str($db->getAll("select id_type, title, group_with from discount_type where id_type = " . $_GET['id']));

        $render->assign('title', $arr_data[0]['title']);
        $render->assign('id', $arr_data[0]['id_type']);

        $render->assign('action_url', "?".$this->getURL());
        $render->assign("edit", 1);

        // Get list types discounts
        $arr_types = $db->getAll("select id_type, title from discount_type where id_type <> {$_GET[id]} order by title asc");
        $render->assign("types_discounts", $arr_types);
        
        // Get list products selected for discount from table with products
        $arr_items = ("" == $arr_data[0]['group_with']|| "0" == $arr_data[0]['group_with']) ? array('0') : split(",", $arr_data[0]['group_with']);
        $list_types = "0";
        $list_discounts = "0";
        foreach($arr_items as $item)
        {
            if (strstr($item, "t"))
                $list_types .= ", " . substr($item, 1, strlen($item) - 1);
            else if (strstr($item, "d"))
                $list_discounts .= ", " . substr($item, 1, strlen($item) - 1);
        }
        $arr_types = $db->getAll("select id_type as id, title from discount_type where id_type in ({$list_types})");        
        $arr_discounts = $db->getAll("select id_discount as id, title from discount where id_discount in ({$list_discounts})");        
        $render->assign("arr_types_selected", $arr_types);
        $render->assign("arr_discounts_selected", $arr_discounts);
    }

    // ----------------------------------------------------------------------------------
    // --- [ Render Discount Type Add Page ] ---------------------------------------------------
    // ----------------------------------------------------------------------------------

    function renderDiscountTypeAdd(&$render, &$db, &$core)
    {
        $render->assign('action_url', "?".$this->getURL());

        // Get list types discounts
        $arr_types = $db->getAll("select id_type, title from discount_type where id_type <> {$_GET[id]} order by title asc");
        $render->assign("types_discounts", $arr_types);
        $render->assign("edit", 0);
    }
};


?>